using DeviceCommons.DeviceMessages.Factories;
using DeviceCommons.DeviceMessages.Models.V1;

namespace ConsoleTestApp
{
    /// <summary>
    /// 简化的演示程序
    /// 展示如何使用新的 DeviceMessageProcessor API
    /// </summary>
    public class SimplifiedDemo
    {
        public static void RunDemo()
        {
            Console.WriteLine("=== 简化API演示 ===\n");

            // 1. 创建处理器并注册设备类型
            var processor = new DeviceMessageProcessor()
                .RegisterDeviceType(1, builder => builder
                    .AddStringState(1, "名称", "设备名称")
                    .AddInt32State(2, "温度", "温度值")
                    .AddBooleanState(3, "状态", "运行状态"))
                .RegisterDeviceType(2, builder => builder
                    .AddStringState(1, "名称", "设备名称")
                    .AddFloat32State(2, "湿度", "湿度值"));

            // 2. 创建和序列化消息
            var message = processor.CreateMessage()
                .WithHeader(version: 0x02)
                .WithMainDevice("Sensor01", 1)
                .AddReading(0, reading => reading
                    .AddState(1, "温度传感器")
                    .AddState(2, 25)
                    .AddState(3, true))
                .Build();

            var hexString = processor.SerializeMessage(message);
            Console.WriteLine($"序列化消息: {hexString}");

            // 3. 解析消息（快速解析）
            var parsedMessage = processor.ParseMessage(hexString, enableFastParsing: true);
            Console.WriteLine("快速解析结果:");
            DisplayMessage(parsedMessage);

            // 4. 解析消息（传统解析）
            var traditionalMessage = processor.ParseMessage(hexString, enableFastParsing: false);
            Console.WriteLine("\n传统解析结果:");
            DisplayMessage(traditionalMessage);

            // 5. 显示统计信息
            var stats = processor.GetStatistics();
            Console.WriteLine($"\n统计信息: {stats.TotalDeviceTypes} 个设备类型, {stats.TotalStates} 个状态");
        }

        private static void DisplayMessage(IDeviceMessage message)
        {
            if (message?.MainDevice == null) return;

            Console.WriteLine($"设备ID: {message.MainDevice.DID}");
            Console.WriteLine($"设备类型: {message.MainDevice.DeviceType}");
            
            if (message.MainDevice.Reading?.ReadingArray != null)
            {
                foreach (var reading in message.MainDevice.Reading.ReadingArray)
                {
                    Console.WriteLine($"读数 - 时间偏移: {reading.TimeOffset}");
                    if (reading.State?.StateArray != null)
                    {
                        foreach (var state in reading.State.StateArray)
                        {
                            Console.WriteLine($"  状态 {state.SID}: {state.ValueText} ({state.ValueType})");
                        }
                    }
                }
            }
        }
    }
}
